import baseurl from './baseurlAnalysis.js'
let ajaxnum = 0;
let loading = false;

const http = (options = {}) => {
    ajaxnum++
    if (ajaxnum == 1 && !loading) {
        loading = true;
        wx.showLoading({ title: '加载中...', mask: true })
    }

    // 初始化headers（确保options.header存在）
    options.header = options.header || {}

    // 统一添加token逻辑
    try {
        const tokenInfo = wx.getStorageSync('studentToken')
        if (tokenInfo) {
            const tokenData = JSON.parse(tokenInfo)
            options.header.Authorization = 'Bearer' + ' ' + tokenData || ''
            // options.header.Authorization = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI4NDA0NDI1MTM1MyIsImxvZ2luX3VzZXJfa2V5IjoiNWIzYzE5ZWItNDdkMi00ZTU2LTkwZTktNDQwZDI0NTJiYzE2In0.tMwWkhPTXG8aiv-Bi3vrAp5G3gxDGiTbV_fmq753sHqVvcwcfUbL-c4Fo5UlY98unI4BjgSeOAizikYCwvk09A'
        }
    } catch (e) {
        console.error('解析token失败:', e)
    }

    return new Promise((resolve, reject) => {
        wx.request({
            url: baseurl.baseUrl + options.url,
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                "content-type": "application/x-www-form-urlencoded",
                ...options.header  // 用户自定义header会覆盖默认
            },
            timeout: options.timeout || 60000,
            success(res) {
                //console.info('res', res)
                if (res.data.code === 401) {
                    handleAuthFailure()
                    return reject(res)  // 显式reject
                }
                resolve(res)
            },
            fail(err) {
                wx.showModal({
                    title: '系统升级中',
                    content: '系统升级中,请稍后重试',
                })
                reject(err)
            },
            complete() {
                ajaxnum--
                if (ajaxnum === 0) {
                    setTimeout(() => {
                        if (ajaxnum === 0) {
                            loading = false;
                            wx.hideLoading()
                        }
                    }, 200)
                }
            }
        })
    })
}
// 统一处理鉴权失败
function handleAuthFailure() {
    wx.showToast({
        title: '登录超时，请重新登录!',
        icon: "none"
    })
    wx.removeStorageSync('newtoken')  // 清除失效token
    wx.navigateTo({
        url: '/pages/newteacherlogin/newteacherlogin'
    })
}
export default http